package com.kaifamiao.thread.d0927;

public class Test {

    public static void main(String[] args) {

        Object lock = new Object();
        Plus plus = new Plus("plus一号", lock);
        Plus plus1 = new Plus("plus二号", lock);
//        Plus plus2 = new Plus("plus三号");

        Minus minus = new Minus("minus一号", lock);
        Minus minus1 = new Minus("minus二号", lock);

        plus.start();
        plus1.start();
        minus.start();
        minus1.start();


        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(Plus.j);
//        plus2.start();
    }
}


class Plus extends Thread {
   public static int j = 0;
//   public static Object lock = new Object();

    private Object lock;
    public Plus(String name) {
        super(name);
    }
    public Plus(String name, Object lock) {
        super(name);
        this.lock = lock;
    }


    @Override
   public void run(){
       for (int i = 0; i < 100; i++) {
           try {
               Thread.sleep(10);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
           synchronized (lock){
               System.out.println(Thread.currentThread().getName() +" 对 j 加一 后是：" + ++ j);
           }
       }
   }

}

class Minus extends Thread {

    private Object lock;

    public Minus(String name) {
        super(name);
    }

    public Minus(String name, Object lock) {
        super(name);
        this.lock = lock;
    }
    @Override
    public void run(){
        for (int i = 0; i < 100; i++) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lock){
                System.out.println(Thread.currentThread().getName() + "对 j 减一后是：" + -- Plus.j );
            }
        }
    }
}
